package com.jhx.demos.web.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jhx.demos.web.mapper.UserMapper;
import com.jhx.demos.web.pojo.BufferMessage;
import com.jhx.demos.web.pojo.PageBean;
import com.jhx.demos.web.pojo.Message;
import com.jhx.demos.web.pojo.User;
import com.jhx.demos.web.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class userServiceimpl implements userService {
    @Autowired
    private UserMapper userMapper;


    //登录校验
    @Override
    public User login(User user) {
//        //1.用用户名查询用户信息，若不存在抛异常
//        if(ObjectUtils.isEmpty(user))throw new RuntimeException("用户名不存在！");
//        //2.若存在，获取加密密码与用户输入密码比较，若不正确抛异常
//        String newPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
//        user.setPassword(newPassword);
//        userMapper.register(user);
        return userMapper.getByusernameandpassword(user);
    }

    //查询全部的信息
//    @Override
//    public List<Message> list() {
//        return userMapper.list();
//    }

    //分页查询
    @Override
    public PageBean page(Integer page, Integer pageSize, Integer publisherID, LocalDate begin, LocalDate end) {
        //1.设置分页参数
        PageHelper.startPage(page, pageSize);

        //2.执行查询
        List<Message> userList = userMapper.list(publisherID, begin, end);
        Page<Message> p = (Page<Message>) userList;//将emplist强转为list类型

        //3.封装pageBean对象
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());//获取总记录数getTotal() 获取结果列表getResult
        return pageBean;
    }

    //新增信息!!!
    @Override
    public void save(BufferMessage bmes) {
    bmes.setDatetime(LocalDateTime.now());
        userMapper.insert(bmes);
        bmes.setDatetime(LocalDateTime.now());
    }

    //批量删除信息
    @Override
    public void delete(List<Integer> ids) {
    userMapper.delete(ids);
    }

    //通过id查询信息
    @Override
    public Message find(Integer id) {

        return userMapper.find(id);
    }

    //进行信息修改
    @Override
    public void update(Message mes) {
        userMapper.update(mes);
    }

    @Override
    public void register(User user) {
//        userMapper.register(user);
//        //判断用户是否存在
//        if(!ObjectUtils.isEmpty(user))throw new RuntimeException("用户名已存在！");
//        //密码MD5加密&&注册用户    MD5：相同字符串多次使用MD5加密，加密结果一致
//        String newPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
//        user.setPassword(newPassword);
        userMapper.register(user);
    }
}
